// 游戏逻辑文件
const canvas = document.getElementById('game-board');
const ctx = canvas.getContext('2d');
const currentPlayerDisplay = document.getElementById('current-player');
const gameStatusDisplay = document.getElementById('game-status');

// 棋盘设置
const BOARD_SIZE = 15; // 棋盘大小（15x15）
const CELL_SIZE = canvas.width / (BOARD_SIZE + 1); // 计算每个单元格的大小
const STONE_RADIUS = CELL_SIZE * 0.45;
let currentTurn = 'black'; // 当前玩家，初始为黑棋
let gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(null)); // 创建二维数组表示棋盘
let moveHistory = []; // 存储移动历史，用于撤销操作

// 初始化游戏
function initGame() {
    drawBoard(); // 绘制棋盘
    
    // 添加点击事件监听器
    canvas.addEventListener('click', handleCanvasClick);
    
    // 新游戏按钮事件监听器
    document.getElementById('new-game').addEventListener('click', startNewGame);
    
    // 撤销按钮事件监听器
    document.getElementById('undo-move').addEventListener('click', undoMove);
}

// 绘制棋盘
function drawBoard() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制外框
    ctx.strokeStyle = '#3b3b3b';
    ctx.lineWidth = 2;
    ctx.strokeRect(CELL_SIZE, CELL_SIZE, canvas.width - 2 * CELL_SIZE, canvas.height - 2 * CELL_SIZE);
    
    // 绘制棋盘线
    ctx.beginPath();
    for (let i = 0; i < BOARD_SIZE; i++) {
        // 横线
        ctx.moveTo(CELL_SIZE, CELL_SIZE + i * CELL_SIZE);
        ctx.lineTo(canvas.width - CELL_SIZE, CELL_SIZE + i * CELL_SIZE);
        
        // 竖线
        ctx.moveTo(CELL_SIZE + i * CELL_SIZE, CELL_SIZE);
        ctx.lineTo(CELL_SIZE + i * CELL_SIZE, canvas.height - CELL_SIZE);
    }
    ctx.stroke();
    
    // 绘制星位
    drawStars();
}

// 绘制星位
function drawStars() {
    const stars = [
        [3, 3], [11, 3], [3, 11], [11, 11], // 四角星位
        [7, 7] // 中心星位
    ];
    
    ctx.fillStyle = '#000';
    
    stars.forEach(([x, y]) => {
        ctx.beginPath();
        ctx.arc((x + 1) * CELL_SIZE, (y + 1) * CELL_SIZE, 5, 0, Math.PI * 2);
        ctx.fill();
    });
}

// 处理画布点击事件
function handleCanvasClick(event) {
    if (gameStatusDisplay.textContent !== '') return; // 如果游戏已经结束则不处理
    
    const rect = canvas.getBoundingClientRect();
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;
    
    // 找到最近的交叉点
    const x = Math.round((mouseX - CELL_SIZE) / CELL_SIZE);
    const y = Math.round((mouseY - CELL_SIZE) / CELL_SIZE);
    
    // 检查是否在棋盘范围内
    if (x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE) {
        // 如果该位置还没有棋子
        if (gameBoard[x][y] === null) {
            placeStone(x, y, currentTurn); // 放置棋子
            moveHistory.push({x, y, player: currentTurn}); // 记录移动
            
            // 检查胜负
            if (checkWin(x, y, currentTurn)) {
                gameStatusDisplay.textContent = `${currentTurn === 'black' ? '黑棋' : '白棋'} 获胜！`;
                return;
            }
            
            // 检查平局
            if (isBoardFull()) {
                gameStatusDisplay.textContent = '平局！';
                return;
            }
            
            // 切换玩家
            currentTurn = currentTurn === 'black' ? 'white' : 'black';
            currentPlayerDisplay.textContent = currentTurn === 'black' ? '黑棋' : '白棋';
        }
    }
}

// 放置棋子
function placeStone(x, y, player) {
    const centerX = (x + 1) * CELL_SIZE;
    const centerY = (y + 1) * CELL_SIZE;
    
    // 绘制棋子
    ctx.beginPath();
    ctx.arc(centerX, centerY, STONE_RADIUS, 0, Math.PI * 2);
    ctx.fillStyle = player === 'black' ? '#000' : '#fff';
    ctx.fill();
    
    // 添加阴影边框
    ctx.strokeStyle = player === 'black' ? '#000' : '#ccc';
    ctx.lineWidth = 2;
    ctx.stroke();
    
    // 更新棋盘状态
    gameBoard[x][y] = player;
}

// 检查胜负
function checkWin(x, y, player) {
    // 定义四个方向：水平、垂直、对角线、反对角线
    const directions = [
        [[1, 0], [-1, 0]], // 水平方向
        [[0, 1], [0, -1]], // 垂直方向
        [[1, 1], [-1, -1]], // 对角线方向
        [[1, -1], [-1, 1]] // 反对角线方向
    ];
    
    // 检查每个方向
    for (const [[dx1, dy1], [dx2, dy2]] of directions) {
        let count = 1; // 包括当前棋子
        
        // 沿着第一个方向检查
        let nx = x + dx1;
        let ny = y + dy1;
        while (nx >= 0 && nx < BOARD_SIZE && ny >= 0 && ny < BOARD_SIZE && gameBoard[nx][ny] === player) {
            count++;
            nx += dx1;
            ny += dy1;
        }
        
        // 沿着第二个方向检查
        nx = x + dx2;
        ny = y + dy2;
        while (nx >= 0 && nx < BOARD_SIZE && ny >= 0 && ny < BOARD_SIZE && gameBoard[nx][ny] === player) {
            count++;
            nx += dx2;
            ny += dy2;
        }
        
        // 如果有五连珠
        if (count >= 5) {
            return true;
        }
    }
    
    return false;
}

// 检查棋盘是否已满
function isBoardFull() {
    return gameBoard.every(row => row.every(cell => cell !== null));
}

// 开始新游戏
function startNewGame() {
    // 重置棋盘
    gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(null));
    moveHistory = [];
    currentTurn = 'black';
    currentPlayerDisplay.textContent = '黑棋';
    gameStatusDisplay.textContent = '';
    
    // 重新绘制棋盘
    drawBoard();
}

// 撤销上一步
function undoMove() {
    if (moveHistory.length > 0) {
        const lastMove = moveHistory.pop();
        
        // 移除棋盘上的棋子
        gameBoard[lastMove.x][lastMove.y] = null;
        
        // 切换玩家
        currentTurn = moveHistory.length % 2 === 0 ? 'black' : 'white';
        currentPlayerDisplay.textContent = currentTurn === 'black' ? '黑棋' : '白棋';
        
        // 重新绘制棋盘
        drawBoard();
        
        // 重新放置剩余的棋子
        for (const move of moveHistory) {
            placeStone(move.x, move.y, move.player);
        }
        
        // 清除游戏状态
        gameStatusDisplay.textContent = '';
    }
}

// 初始化游戏
initGame();

const { createApp, ref } = Vue;

createApp({
  setup() {
    const board = ref(Array(15).fill().map(() => Array(15).fill(null)));
    const currentPlayer = ref('black');
    const gameOver = ref(false);
    const winner = ref(null);

    function makeMove(row, col) {
      if (gameOver.value || board.value[row][col] !== null) {
        return;
      }
      
      // Make the move
      board.value[row][col] = currentPlayer.value;
      
      // Check for win
      if (checkWin(row, col)) {
        gameOver.value = true;
        winner.value = currentPlayer.value;
      }
      
      // Switch player
      currentPlayer.value = currentPlayer.value === 'black' ? 'white' : 'black';
    }

    function checkWin(row, col) {
      const directions = [
        [[0, 1], [0, -1]],  // 横向
        [[1, 0], [-1, 0]], // 纵向
        [[1, 1], [-1, -1]], // 对角线
        [[-1, 1], [1, -1]]  // 另一条对角线
      ];
      
      for (const [[dx1, dy1], [dx2, dy2]] of directions) {
        let count = 1;
        
        // 检查一个方向
        let x = row + dx1;
        let y = col + dy1;
        while (x >= 0 && x < 15 && y >= 0 && y < 15 && board.value[x][y] === currentPlayer.value) {
          count++;
          x += dx1;
          y += dy1;
        }
        
        // 检查相反方向
        x = row + dx2;
        y = col + dy2;
        while (x >= 0 && x < 15 && y >= 0 && y < 15 && board.value[x][y] === currentPlayer.value) {
          count++;
          x += dx2;
          y += dy2;
        }
        
        if (count >= 5) {
          return true;
        }
      }
      
      return false;
    }

    function resetGame() {
      board.value = Array(15).fill().map(() => Array(15).fill(null));
      currentPlayer.value = 'black';
      gameOver.value = false;
      winner.value = null;
    }

    return {
      board,
      currentPlayer,
      gameOver,
      winner,
      makeMove,
      resetGame
    };
  }
}).mount('#app');
